package com.dyrnq.seckill.config;


import com.dyrnq.seckill.controller.Result;
import com.dyrnq.seckill.exception.UnauthorizedException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@ControllerAdvice
@Slf4j
public class WebGlobalExceptionHandler {
    @ExceptionHandler({RuntimeException.class})
    @ResponseBody
    public ResponseEntity<Result<String>> runtimeExceptionHandler(RuntimeException exception) {
        log.error(exception.getMessage(), exception);
        int status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
        Result<String> errorResponse = new Result<>(status, exception.getMessage(), null);
        return ResponseEntity.status(status)
                .contentType(MediaType.APPLICATION_JSON)
                .body(errorResponse);
    }
    @ExceptionHandler({UnauthorizedException.class})
    @ResponseBody
    public ResponseEntity<Result<String>> unauthorizedExceptionHandler(UnauthorizedException exception) {
        log.error(exception.getMessage(), exception);
        int status = HttpServletResponse.SC_UNAUTHORIZED;
        Result<String> errorResponse = new Result<>(status, exception.getMessage(), null);
        return ResponseEntity.status(status)
                .contentType(MediaType.APPLICATION_JSON)
                .body(errorResponse);
    }

}
